<template>
  <NuxtLayout>
    <div class="login-box">
      <div class="main-box">
        <div class="login-top">
          <a href="/">技考邦首页</a>
          <div class="shu">|</div>
          <a href="/mechanism">机构入驻</a>
        </div>
        <div class="login-main">
          <img src="https://static.dzyxzx.cn/jkbpc%2Flogimg.png" alt="">
          <div class="title">
            <p>技考邦</p>
            <p class="title-p">一站式技考学习平台</p>
          </div>
          <el-tabs v-model="loginTabValue" stretch @tab-click="loginTabClickFn">
            <el-tab-pane label="密码登录" name="1">
              <div class="sms-log">
                <el-input v-model="phone" maxlength="11" placeholder="请输入手机号" autocomplete="off"></el-input>
                <el-input v-model="psw" placeholder="请输入密码" autocomplete="off" type="password" show-password>
                </el-input>
                <!-- <el-checkbox v-model="check1" label="7天免登录"></el-checkbox> -->
                <el-button type="primary" style="width: 360px; height: 48px;" :disabled="loginDisabled"
                  @click=getLogin()>登录</el-button>
                <div class="read">
                  <el-checkbox v-model="check2"></el-checkbox>
                  <span>&ensp;我已阅读并同意<a href="/user_agreement" target="_blank">《用户协议》</a>和<a href="/privacy_policy"
                      target="_blank">《隐私政策》</a></span>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="短信登录" name="2">
              <div class="sms-log">
                <el-input v-model="shortPhone" maxlength="11" placeholder="请输入手机号" autocomplete="off"></el-input>
                <el-input v-model="code" placeholder="请输入验证码" autocomplete="off">
                  <template #append>
                    <el-button id="btn" :disabled="isShow" @click="sendCode">{{ downTimeText }}</el-button>
                  </template>
                </el-input>
                <el-button type="primary" style="width: 360px; height: 48px;" :disabled="loginDisabled"
                  @click=loginByCode()>登录</el-button>
                <div class="read">
                  <el-checkbox v-model="check2"></el-checkbox>
                  <span>&ensp;我已阅读并同意<a href="/user_agreement" target="_blank">《用户协议》</a>和<a href="/privacy_policy"
                      target="_blank">《隐私政策》</a></span>
                  <div>未注册过的手机号，我们将自动为您注册账号</div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
  </NuxtLayout>
</template>

<script setup>
import { getPhoneCodeApi, loginByCodeNumApi, loginByPasswordApi, getUserInfoApi } from '~/server/api'
// import { useToken } from '~/store/token'
definePageMeta({ layout: false })
import { useRoute, useRouter } from 'vue-router';
import { useToken, useUserinfo } from '~/store';
const { setToken } = useToken();
const { setUserinfo } = useUserinfo();
const route = useRoute();
const router = useRouter();
// TDK
const prevHost = useRequestHeaders()["x-forwarded-proto"];
const host = useRequestHeaders()["host"];
const fullPath = route["fullPath"];
useSeoMeta({
  title: '技考邦_短信登录_密码登录',
  keywords: '技考邦,短信登录,密码登录',
  description: '技考邦，短信登录，密码登录。',
  ogTitle: '技考邦_短信登录_密码登录',
  ogDescription: '技考邦，短信登录，密码登录。',
  ogType: "article",
  ogUrl: `${prevHost}://${host}${fullPath}`,
})
const loginTabValue = ref('1')
const shortPhone = ref('')
const phone = ref('')
const code = ref('')
const psw = ref('')
let downTime = 60
let downTimeText = ref('获取验证码')
const isShow = ref(false)
// const check1 = ref(false)
const check2 = ref(true)
const activeName = ref('0')
const loginDisabled = ref(false)
// 短信 密码登录切换
const loginTabClickFn = (e) => {
  loginTabValue.value = e.props.name;
}
//获取验证码
const sendCode = () => {
  const reg = /^1[3-9]\d{9}$/
  if (!reg.test(shortPhone.value)) {
    ElMessage({
      message: '请输入正确的手机号',
      type: 'error'
    })
  } else {
    //获取验证码
    useServerRequest(getPhoneCodeApi, {
      method: 'get',
      params: { phone: shortPhone.value }
    }).then(res => {
      if (res.errno === 0) {
        //按钮倒计时
        isShow.value = true;
        var remainTime = downTime;
        downTimeText.value = `重新获取${remainTime}s`
        let timer = setInterval(() => {
          remainTime = remainTime - 1;
          downTimeText.value = `重新获取${remainTime}s`;
          if (remainTime < 1) {
            clearInterval(timer)
            remainTime = downTime;
            downTimeText.value = '获取验证码';
            isShow.value = false;
            return false
          }
        }, 1000)
      }
    })
  }
}
//验证码登录
const loginByCode = async () => {
  if (check2.value === false) {
    ElMessage({
      message: '请先阅读并勾选同意协议',
      type: 'warning'
    })
  } else {
    loginDisabled.value = true;
    await useServerRequest(loginByCodeNumApi, {
      method: 'post',
      body: JSON.stringify({ phoneNo: shortPhone.value, phoneCode: code.value })
    }).then(res => {
      if (res.errno === 0) {
        useToken().token = res.result.token;
        // setToken(res.result.token)
        getUserFn()
        // useRouter().push('/')
        // window.location.href = '/';
        ElMessage({
          message: '登录成功！',
          type: 'success'
        })
        return false;
      }
      loginDisabled.value = false;
    }).catch(err => {
      loginDisabled.value = false;
    })
  }
}
//密码登录
const getLogin = async () => {
  if (!phone.value) {
    ElMessage({
      message: '请输入手机号',
      type: 'error'
    })
  } else {
    if (!psw.value) {
      ElMessage({
        message: '请输入密码',
        type: 'error'
      })
    } else {
      if (check2.value === false) {
        ElMessage({
          message: '请先阅读并勾选同意协议',
          type: 'warning'
        })
      } else {
        loginDisabled.value = true;
        await useServerRequest(loginByPasswordApi, {
          method: 'post',
          body: JSON.stringify({ phoneNo: phone.value, password: psw.value }
          )
        }).then(res => {
          if (res && res.errno === 0 && res.result) {
            //记住密码
            // if (check1.value === true) {
            //   let now = new Date()
            //   now.setDate(now.getDate() + 7)
            //   let time7 = now.getTime()
            //   localStorage.setItem('time7', time7)
            //   localStorage.setItem('a', phone.value)
            //   localStorage.setItem('p', psw.value)
            // }
            //设置token
            useToken().token = res.result.token;
            // setToken(res.result.token)
            // 获取用户信息
            // to.meta.userinfo = null;
            getUserFn()
            // window.location.href = '/';
            ElMessage({
              message: '登录成功！',
              type: 'success'
            })
            return false
          }
          loginDisabled.value = false;
        }).catch(err => {
          loginDisabled.value = false;
        })
      }
    }
  }
}
// 获取用户信息
const getUserFn = () => {
  useAsyncData('getUserInfoApi', () => useServerRequest(getUserInfoApi, {
    method: 'get'
  })).then(({ data: { value: res } }) => {
    if (res && res.errno === 0 && res.result) {
      route.meta.userinfo = res.result;
      setUserinfo(res.result)
      router.push('/')
    }
  })
}
// 挂载后
onMounted(() => {
  // 记住密码
  let time7 = localStorage.getItem('time7')
  let cTime7 = new Date().getTime()
  if (time7 && cTime7) {
    if (time7 - cTime7 <= 0) { // 7天已过
      localStorage.removeItem('a')
      localStorage.removeItem('p')
    } else { // 7天内
      phone.value = localStorage.getItem('a')
      psw.value = localStorage.getItem('p')
    }
  }
})
</script>

<style lang="less">
.login-box {
  .el-tabs {
    width: 360px;
    position: relative;
    top: 80px;
    left: 580px;
  }

  .el-tabs__item {
    font-size: 20px;
    font-weight: bold;

    &:hover {
      color: #0074FC;
    }
  }

  .el-tabs__item.is-active {
    color: #0074FC;
  }

  .el-tabs__active-bar {
    height: 3px;
    color: #0074FC;
  }

  .el-checkbox__input {
    width: 19px;
    height: 19px;
  }

  .el-checkbox__inner {
    width: 19px;
    height: 19px;

    &::after {
      width: 7px;
      height: 12px;
    }
  }

  .el-checkbox__label {
    margin-top: 2px;
  }

  .sms-log {

    .el-input {
      width: 360px;
      height: 48px;
    }

    >.el-button {
      background-color: #0074FC;
      font-size: 20px;
    }

    .el-input-group__append {
      background: #fff;
      border: none;
    }

    .el-input-group--append {
      .el-input__wrapper {
        // box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color)) inset;
        box-shadow: none;
        border: 1px solid #dcdfe6;
        border-right: none;
      }
    }

    .el-checkbox__input.is-checked {
      color: #0074FC;
    }
  }
}
</style>
<style lang="less" scoped>
.login-box {
  display: flex;
  justify-content: center;
  align-content: center;
  background-color: rgba(0, 116, 252, 0.10);

  .main-box {
    width: 1065px;
    position: relative;
    height: 911px;

    .login-top {
      margin-top: 19px;
      color: #666;
      display: flex;
      justify-content: end;

      >span {
        cursor: pointer;

        &:hover {
          color: #FF3F29;
        }
      }

      >a {
        color: #666;
      }

      .shu {
        padding: 0 10px;
      }
    }

    .login-main {
      height: 560px;
      margin-top: 130px;
      background-color: #fff;
      display: block;
      position: relative;

      img {
        position: absolute;
        left: -20px;
        top: -40px;
      }

      .title {
        z-index: 99;
        position: absolute;
        width: 489px;
        color: #fff;
        font-size: 30px;
        left: 55px;

        .title-p {
          font-size: 36px;
        }
      }
    }
  }
}

.login-box .el-tab-pane {
  width: 360px;
  height: 355px;
}

.sms-log {
  width: 360px;
  height: 355px;
  margin-top: 15px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-content: center;

  .read {
    font-size: 14px;
    display: flex;
    justify-content: left;
    align-items: center;
    flex-wrap: wrap;

    >span {
      margin-top: -2px;

      a {
        color: #0074FC;
      }
    }

    >div {
      color: #999;
      margin-left: 21px;
    }
  }
}

.scan-box {
  width: 360px;
  height: 355px;
  margin-top: 15px;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  align-items: center;
}

.img-box {
  width: 248px;
  height: 248px;
  background-color: pink;
}
</style>